package qualomelhor.server;


import java.io.IOException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.*;
import javax.mail.internet.AddressException;
import com.google.appengine.api.mail.*; 


public class EnviaContato {

	public static void sendAppEmail(String[] emailDestino, String assunto, String body, String contentType) {
		Properties props = new Properties(); 
		props.setProperty("charset", "UTF-8");
		props.setProperty("mail.mime.charset", "UTF-8");
		Session session = Session.getDefaultInstance(props, null);  
		
		boolean emailAdmin = false;

		try { 

			Message msg = new MimeMessage(session); 
			msg.setFrom(new InternetAddress("o.que.e.melhor@gmail.com"));
			if (emailDestino.length == 0) {
				msg.addRecipient(Message.RecipientType.TO, new InternetAddress("o.que.e.melhor@gmail.com"));
				System.out.println("email unico para rodteixo2!");
			} else if (emailDestino.length == 1 && emailDestino[0].equals("o.que.e.melhor@gmail.com")) {
				emailAdmin = true;
			} else {
				for (int i = 0; i < emailDestino.length; i++) {
					msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailDestino[i]));
				}
			}

			try {
				msg.setSubject(MimeUtility.encodeText(assunto,"UTF-8", "B"));	
			} catch (java.io.UnsupportedEncodingException e) {
				System.out.println("Erro no encoding do mail subject!!");
				e.printStackTrace();
			}

			Multipart mp = new MimeMultipart(); 			
			MimeBodyPart htmlPart = new MimeBodyPart(); 
			//htmlPart.setText(body, "ISO-8859-1");
	        htmlPart.setContent(body, contentType); 
	        mp.addBodyPart(htmlPart); 
	        msg.setContent(mp);

	        if (emailAdmin) {
	        	 MailService.Message msg1 = new MailService.Message(); 
	             msg1.setSender("o.que.e.melhor@gmail.com"); 
	             msg1.setSubject(assunto); 
	             msg1.setTextBody(body); 
	             MailServiceFactory.getMailService().sendToAdmins(msg1);
	        } else {
	        	Transport.send(msg);
	        }

		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public EnviaContato () {

	}
}